<template>
  <div class="app-container" style="height: 100%;">
    <div class="app-container-inner" v-loading="loading" element-loading-text="加载中...">
      <div class="header flex-justify-between">
        <div class="btns flex-align-center">
          <el-button class="btn btn-bg mr5" @click="addList">新增角色</el-button>
          <el-dropdown trigger="click">
            <el-button class="btn btn-bg5 btn-all"
              :style="selecttion.length == 0 ? 'border: 1px solid #ccc;color:#999' : ''"
              :disabled="selecttion.length == 0">
              <img :src="batch" class="iconfont mr5" alt="" sizes="16" srcset="" />批量操作
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="useAll">
                  <el-icon>
                    <CircleCheck />
                  </el-icon>批量启用
                </el-dropdown-item>
                <el-dropdown-item @click="disableAll">
                  <el-icon>
                    <Warning />
                  </el-icon>批量禁用
                </el-dropdown-item>
                <el-dropdown-item @click="deleAll">
                  <el-icon>
                    <Delete />
                  </el-icon>批量删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="search flex-align-center">
          <el-input clearable v-model="keyword" placeholder="关键词搜索" class="input-width" @keyup.enter.native="searchList">
          </el-input>
          <button class="btn btn-bg1" @click="searchList">
            <el-icon class="mr5">
              <Search />
            </el-icon>搜索
          </button>
        </div>
      </div>
      <div class="table-role">
        <el-table border stripe resizable :data="tableData" ref="tableList" @selection-change="handleChange" height="100%"
          style="position: absolute;">
          <el-table-column type="selection" width="40" :selectable="checkDisable" />
          <el-table-column show-overflow-tooltip type="index" label="序号" width="50" />
          <el-table-column show-overflow-tooltip prop="name" label="角色名称" min-width="150" />
          <el-table-column show-overflow-tooltip prop="code" label="角色编码" min-width="150" />
          <el-table-column show-overflow-tooltip prop="disabled" label="状态" width="70">
            <template #default="scope">
              <el-tag v-if="!scope.row.status" type="success">启用</el-tag>
              <el-tag v-if="scope.row.status" type="info">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="updateTime" label="创建时间" width="130" />
          <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="130" />
          <el-table-column show-overflow-tooltip fixed="right" label="操作" width="60">
            <template #default="scope">
              <div class="btns flex-justify-between">
                <span class="btn_table" @click="viewDetail(scope.row)">编辑</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="footer">
        <Pagination ref="pagination" :list_total="total" @size-change="getList" @current-change="getList" />
      </div>
      <!-- 角色弹窗 -->
      <el-dialog class="edit-dialog" v-model="editDialog" :title="ruleForm.id ? '编辑角色' : '添加角色'" width="330px"
        :draggable="true" :destroy-on-close="true" :close-on-click-modal="false" top="12vh">
        <div class="form-text" :class="isAdmin == true ? '' : 'mb10'">
          <el-form label-width="80" ref="ruleFormRef" :rules="rules" :model="ruleForm">
            <el-form-item label="角色名称" class="form-item" prop="name">
              <el-input clearable v-model="ruleForm.name" class="item-input" :disabled="isAdmin == true"
                placeholder="请输入名称" />
            </el-form-item>
            <el-form-item label="角色编码" class="form-item">
              <el-input clearable v-model="ruleForm.code" class="item-input" :disabled="isAdmin == true"
                placeholder="请输入编码" />
            </el-form-item>
            <el-form-item label="角色状态" :class="isAdmin == true ? '' : 'form-item'">
              <el-radio-group v-model="ruleForm.status">
                <el-radio :label="false" :disabled="isAdmin == true">
                  <span class="bg_text">启用</span>
                </el-radio>
                <el-radio :label="true" :disabled="isAdmin == true">
                  <span class="bg_text">禁用</span>
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
        <div :class="ruleForm.id ? 'flex-justify-between' : 'btns'" v-show="isAdmin == false">
          <div class="left" v-if="ruleForm.id">
            <el-button color="#f56c6c" class="btn_delete" @click="deleteRole">删除</el-button>
          </div>
          <div class="right">
            <el-button @click="editDialog = false" class="btn_cancel"> 取消 </el-button>
            <el-button @click="submitForm(ruleFormRef)" color="#007cff" class="btn_save">保存</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
  
<script setup lang="ts">
import batch from '@/assets/image/batch.png'
import Pagination from '@/components/Pagination/index.vue'
import { Search, Delete, Warning } from '@element-plus/icons-vue'
import { ref, onMounted, markRaw, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { getRoleList, changeRole, deleRole, saveRole, getDetailEmp } from '../../../api/role'

const loading = ref(false)
const editDialog = ref(false)
const assignDialog = ref(false)
const tableData = ref([]) // 角色列表
const total = ref() // 总数量
const limit = ref() // 每页显示数量
const page = ref() // 当面页码
const keyword = ref('') // 搜索关键词
const pagination = ref() // 分页dom
const tableList = ref() // 列表dom
const isAdmin = ref(false) // 是否是超管

// 表单数据
const ruleForm = ref({
  id: '',
  name: '', // 角色名称
  code: '', // 角色编码
  status: false//角色状态 false-正常，true-禁用
})

// 表单元素
const ruleFormRef = ref<FormInstance>()

// 验证规则
const rules = reactive({
  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
})

// 获取角色列表
const getList = async () => {
  loading.value = true
  limit.value = pagination.value.size
  page.value = pagination.value.current
  const data = {
    keyword: keyword.value,
    limit: limit.value,
    page: page.value,
  }
  await getRoleList(data).then((res: any) => {
    total.value = parseInt(res.data.data.total)
    loading.value = false
    tableData.value = res.data.data.rows
  })
}

onMounted(() => {
  getList()
})

// 获取表格选中的数据
const selecttion = ref([])
const handleChange = (val: any) => {
  if (val.length != 0) {
    val.forEach((item) => {
      if (selecttion.value.indexOf(item.id) == -1) {
        selecttion.value.push(item.id)
      } else {
        selecttion.value = selecttion.value.filter((i) => i == item.id)
      }
    })
  } else {
    selecttion.value = []
  }
}

// 判断是否可选
const checkDisable = (row) => {
  if (row.admin == true) {
    return false // 可选
  } else {
    return true // 不可选
  }
}

// 添加角色
const addList = () => {
  ruleForm.value = {
    id: '',
    name: '', // 角色名称
    code: '', // 角色编码
    status: false
  }
  editDialog.value = true
}

// 保存角色
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      await saveRole(ruleForm.value).then((res) => {
        if (res.data.success == true) {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 2000,
          })
          editDialog.value = false
          getList()
        } else {
          ElMessage({
            message: res.data.message,
            type: 'warning',
            duration: 2000,
          })
          return
        }
      })

    } else {
      console.log('error submit!')
      return
    }
  })
}

// 删除角色
const deleteRole = () => {
  let tmp = []
  tmp.push(ruleForm.value.id)
  ElMessageBox({
    type: 'error',
    icon: markRaw(Delete),
    title: '提示',
    message: '确认删除该角色?',
    showCancelButton: true,
    closeOnClickModal: false,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        instance.confirmButtonText = '加载中...'
        setTimeout(() => {
          done()
          setTimeout(() => {
            instance.confirmButtonLoading = false
          }, 0)
        }, 500)
      } else {
        done()
      }
    },
  }).then(async () => {
    await deleRole(tmp).then((res: any) => {
      ElMessage({
        message: res.data.message,
        type: 'success',
        duration: 2000,
      })
    })
    selecttion.value = []
    editDialog.value = false
    tableList.value.clearSelection()
    getList()
  })
}

// 查看角色详细
const viewDetail = async (obj: any) => {
  isAdmin.value = obj.admin
  let res = await getDetailEmp(obj.id)
  ruleForm.value = res.data.data.row
  editDialog.value = true
}

// 搜索角色
const searchList = () => {
  getList()
}

// 批量启用
const useAll = () => {
  if (selecttion.value.length == 0) {
    ElMessage({
      message: '请选择要启用的角色',
      type: 'warning',
      duration: 2000,
    })
    return
  }
  ElMessageBox({
    title: '提示',
    message: '确认启用选中的角色?',
    showCancelButton: true,
    closeOnClickModal: false,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        instance.confirmButtonText = '加载中...'
        setTimeout(() => {
          done()
          setTimeout(() => {
            instance.confirmButtonLoading = false
          }, 0)
        }, 500)
      } else {
        done()
      }
    },
  }).then(async () => {
    await changeRole(selecttion.value, { status: ruleForm.value.status }).then((res: any) => {
      ElMessage({
        message: res.data.message,
        type: 'success',
        duration: 2000,
      })
    })
    selecttion.value = []
    tableList.value.clearSelection()
    getList()
  })
}

// 批量禁用
const disableAll = () => {
  if (selecttion.value.length == 0) {
    ElMessage({
      message: '请选择要禁用的角色',
      type: 'warning',
      duration: 2000,
    })
    return
  }
  ElMessageBox({
    type: 'warning',
    icon: markRaw(Warning),
    title: '提示',
    message: '确认禁用选中的角色?',
    showCancelButton: true,
    closeOnClickModal: false,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        instance.confirmButtonText = '加载中...'
        setTimeout(() => {
          done()
          setTimeout(() => {
            instance.confirmButtonLoading = false
          }, 0)
        }, 1000)
      } else {
        done()
      }
    },
  }).then(async () => {
    await changeRole(selecttion.value, { status: ruleForm.value.status }).then((res: any) => {
      ElMessage({
        message: res.data.message,
        type: 'success',
        duration: 2000,
      })
    })
    selecttion.value = []
    tableList.value.clearSelection()
    getList()
  })
}

// 批量删除
const deleAll = () => {
  if (selecttion.value.length == 0) {
    ElMessage({
      message: '请选择要删除的角色',
      type: 'warning',
      duration: 2000,
    })
    return
  }
  ElMessageBox({
    type: 'error',
    icon: markRaw(Delete),
    title: '提示',
    message: '确认删除选中的角色?',
    showCancelButton: true,
    closeOnClickModal: false,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        instance.confirmButtonText = '加载中...'
        setTimeout(() => {
          done()
          setTimeout(() => {
            instance.confirmButtonLoading = false
          }, 0)
        }, 1000)
      } else {
        done()
      }
    },
  }).then(async () => {
    loading.value = true
    await deleRole(selecttion.value).then((res: any) => {
      ElMessage({
        message: res.data.message,
        type: 'success',
        duration: 2000,
      })
    })
    selecttion.value = []
    tableList.value.clearSelection()
    getList()
  })
}
</script>
  
<style scoped lang="scss">
@import './index';
</style>
  